<?php if(!defined('CALL')) exit('No direct script access allowed');

include_once 'lib/logger.class.php';
include_once 'models/db.class.php';
include_once 'models/m_user.class.php';
include_once 'models/m_events.class.php';


class mEvent
{
	private $uid = null;
	private $dt_beg  = null;
	private $parts   = null;
	private $access  = null;
	private $note    = null;
	
	private $sour_id = null;
	private $dest_id = null;
	private $categ   = null;
	
	public function __construct($email, $dt_beg, $parts, $access, $note, $sour_id, $categ)
	{
		$this->uid = mUser::get_id($email, null);
		$this->dt_beg = $dt_beg;
		$this->parts = $parts;
		$this->access = $access;
		$this->note = $note;
		
		$this->sour_id = $sour_id;
		$this->categ = $categ;
		
		Logger::$log_file = $log_imp_name;
	}
	
	// Принимает объект узла simplexml
	// <event usermail="albert.mavrin@gmail.com" dt="2012-04-20" access="A" parts="NNYY" note="Уличные гуляния " />
	public static function Parse($XmlEvent)
	{
		return new mEvent($XmlEvent['email'], $XmlEvent['dt'], $XmlEvent['parts'], $XmlEvent['access'], $XmlEvent['note'], $XmlEvent['id'], $XmlEvent['categ']);
	}
	
	public function Save()
	{
		if($this->Exists())
			return false;
		else
			$this->dest_id = mEvents::insert($this->uid, $this->dt_beg, $this->parts, $this->access, $this->note);
	}
	
	private function Exists()
	{
		$sql = "SELECT null FROM imports WHERE sour_id = $this->sour_id";
		$this->Log('SQL: '.$sql);
		
		$res = DB::get()->query($sql);
		$num = DB::get()->num_rows($res);
		return $num > 0;
	}
	
	public function Fix()
	{
		$sql = "INSERT INTO imports(categ, sour_id, dest_id) ".
			"VALUES('$this->categ', $this->sour_id, $this->dest_id)";
		$this->Log('SQL: '.$sql);
		
		$res = DB::get()->query($sql);
		$event_id = DB::get()->insert_id();
	}
	
	private function Log($msg)
	{ 
		$ymd = date("Y-m-d", mktime());
		$fd = fopen("logs/import.".$ymd.".log", "a+");
		$str  = date("H:i:s", mktime());
		$str .= "\t".$_SERVER['REMOTE_ADDR'];
		$str .= "\t".$msg."\n";
		fwrite($fd, $str);
		fclose($fd);
	}
}